1 using UnityEngine;
2 using UnityEngine.UI;
3 using System.Collections;
4
5 public class AlphaButtonClickMask : MonoBehaviour, ICanvasRaycastFilter
6 {
7 protected Image _image;
8
9 public void Start()
10 {
11 _image = GetComponent<Image>();
12
13 Texture2D tex = _image.sprite.texture as Texture2D;
14
15 bool isInvalid = false;
16 if (tex != null)
17 {
18 try
19 {
20 tex.GetPixels32();
21 }
22 catch (UnityException e)
23 {
24 Debug.LogError(e.Message);
25 isInvalid = true;
26 }
27 }
28 else
29 {
30 isInvalid = true;
31 }
32
33 if (isInvalid)
34 {
35 Debug.LogError("This script need an Image with a readbale Texture2D to work.");
36 }
37 }
38
39 public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
40 {
41 Vector2 localPoint;
42 RectTransformUtility.ScreenPointToLocalPointInRectangle(_image.rectTransform, sp, eventCamera, out localPoint);
43
44 Vector2 pivot = _image.rectTransform.pivot;
45 Vector2 normalizedLocal = new Vector2(pivot.x + localPoint.x / _image.rectTransform.rect.width, pivot.y + localPoint.y / _image.rectTransform.rect.height);
46 Vector2 uv = new Vector2(
47 _image.sprite.rect.x + normalizedLocal.x * _image.sprite.rect.width,
48 _image.sprite.rect.y + normalizedLocal.y * _image.sprite.rect.height );
49
50 uv.x /= _image.sprite.texture.width;
51 uv.y /= _image.sprite.texture.height;
52
53 //uv are inversed, as 0,0 or the rect transform seem to be upper right, then going negativ toward lower left...
54 Color c = _image.sprite.texture.GetPixelBilinear(uv.x, uv.y);
55
56 return c.a> 0.1f;
57 }
58 }